package com.example.royalchef.fragment;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.example.royalchef.R;
import com.example.royalchef.activity.DynamicCommentActivity;
import com.example.royalchef.activity.LoginActivity;
import com.example.royalchef.activity.SendDynamicActivity;
import com.example.royalchef.activity.ShowBogImageActivity;
import com.example.royalchef.base.BaseFragment;
import com.example.royalchef.base.BaseRecyclerViewAdapter;
import com.example.royalchef.base.BaseRecyclerViewHolder;
import com.example.royalchef.bean.DynamicInfo;
import com.example.royalchef.bean.MessageEvent;
import com.example.royalchef.utils.PreferUtils;
import com.example.royalchef.utils.UIUtils;
import com.example.royalchef.view.CircleImageView;
import com.example.royalchef.view.CustomRecyclerView;
import com.example.royalchef.view.DividerItemDecoration;
import com.example.royalchef.view.ThreeImageView;
import com.squareup.picasso.Picasso;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * author: Administrator
 * created on: 2017/6/27 9:43
 * description:
 */

public class DynamicFragment extends BaseFragment {

    @BindView(R.id.rcv_dynamic)
    CustomRecyclerView mRecyclerView;
    private View mInflate;
    private ArrayList<DynamicInfo> mDynamicInfos;
    private LinearLayoutManager manager;
    private DividerItemDecoration decoration;
    private static final int RESULT = 3;
    private ArrayList<String> checkList;
    private DynamicAdapter adapter;
    private String shareId;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        mInflate = View.inflate(getActivity(), R.layout.fragment_dynamic, null);
        //需要注意的是:这里注册必须满足viewpager缓存全部的页面,不然会蹦,至于为什么我也不知道
        EventBus.getDefault().register(this);
        ButterKnife.bind(this, mInflate);
        initView();
        initData();
        return mInflate;
    }

    private void initView() {
        manager = new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false);
        decoration = new DividerItemDecoration(getContext(), DividerItemDecoration.VERTICAL_LIST);
        mRecyclerView.setLayoutManager(manager);
        mRecyclerView.addItemDecoration(decoration);

    }

    private void initData() {
        mDynamicInfos = new ArrayList<>();
        RequestQueue queue = Volley.newRequestQueue(getContext());
        StringRequest stringRequest = new StringRequest(Request.Method.GET, "http://192.168.12.248:8080/share/list.json?page=0&limit=7",
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        try {
                            JSONObject object = new JSONObject(response);
                            JSONArray data = object.getJSONArray("data");
                            for (int i = 0; i < data.length(); i++) {
                                JSONObject jsonObject = data.getJSONObject(i);
                                shareId = jsonObject.getString("shareId");
                                String comment = jsonObject.getString("commentCount");
                                String content = jsonObject.getString("content");
                                String time = jsonObject.getString("createdAt");
                                String images = jsonObject.getString("images");
                                ArrayList<String> imageList = new ArrayList<>();
                                List<String> list = Arrays.asList(images.split(","));
                                for (String s : list) {
                                    imageList.add(s);
                                }
                                JSONObject user = jsonObject.getJSONObject("user");
                                String avatar = user.getString("avatar");
                                String name = user.getString("nickname");
                                mDynamicInfos.add(new DynamicInfo(avatar, name, time, content, imageList, "成都", "0", comment, "0"));
                            }
                            adapter = new DynamicAdapter(mDynamicInfos, getActivity(), R.layout.item_dynamic);
                            mRecyclerView.setAdapter(adapter);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
            }
        });
        queue.add(stringRequest);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void helloEventBus(MessageEvent messageEvent) {
        String content = messageEvent.getContent();
        checkList = messageEvent.getCheckList();
        String name = PreferUtils.getString("name", "");
        String avatar = PreferUtils.getString("avatar", "");
        mDynamicInfos.add(new DynamicInfo(avatar, name, "2017/02/21", content, checkList, "成都", "32", "16", "63"));
        adapter.notifyDataSetChanged();


    }


    @OnClick(R.id.fab_add_dynamic)
    public void floatingButton(View view) {
        if (TextUtils.isEmpty(PreferUtils.getString("authToken", ""))) {
            Intent intent = new Intent(getActivity(), LoginActivity.class);
            startActivity(intent);
        } else {
            Intent intent = new Intent(getActivity(), SendDynamicActivity.class);
            startActivityForResult(intent, RESULT);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    class DynamicAdapter extends BaseRecyclerViewAdapter<DynamicInfo> {

        private ArrayList<String> checkList;
        private Context context;

        public DynamicAdapter(ArrayList<DynamicInfo> list, Context context, int layoutId) {
            super(list, context, layoutId);
        }

        @Override
        public void convert(BaseRecyclerViewHolder holder, final DynamicInfo dynamicInfo, int position, final Context context) {
            this.context = context;
            checkList = dynamicInfo.getCheckList();

            CircleImageView civAvatar = (CircleImageView) holder.getView(R.id.civ_dynamic_item_avatar);
            TextView tvName = (TextView) holder.getView(R.id.tv_dynamic_item_name);
            TextView tvTime = (TextView) holder.getView(R.id.tv_dynamic_item_time);
            TextView tvTitle = (TextView) holder.getView(R.id.tv_dynamic_item_title);
            RecyclerView rcvDynamicImage = (RecyclerView) holder.getView(R.id.rcv_dynamic_image);
            TextView tvAddress = (TextView) holder.getView(R.id.tv_dynamic_item_address);
            TextView tvBrowse = (TextView) holder.getView(R.id.tv_dynamic_item_browse);
            TextView tvComment = (TextView) holder.getView(R.id.tv_dynamic_item_comment);
            final TextView tvGood = (TextView) holder.getView(R.id.tv_dynamic_item_good);
            LinearLayout Goods = (LinearLayout) holder.getView(R.id.goods);
            LinearLayout Comment = (LinearLayout) holder.getView(R.id.ll_dynamic_comment);

            Picasso.with(context)
                    .load(dynamicInfo.getAvatar())
                    .resize(UIUtils.dip2px(50), UIUtils.dip2px(50))
                    .centerCrop()
                    .config(Bitmap.Config.RGB_565)
                    .into(civAvatar);
            tvName.setText(dynamicInfo.getName());
            tvTime.setText(dynamicInfo.getTime());
            tvTitle.setText(dynamicInfo.getTitle());

            LinearLayoutManager manager = new LinearLayoutManager(context, LinearLayoutManager.HORIZONTAL, false);
            DividerItemDecoration decoration = new DividerItemDecoration(context, DividerItemDecoration.HORIZONTAL_LIST);
            decoration.setWidth(UIUtils.dip2px(5));
            DynamicAdapter.MyAdapter adapter = new DynamicAdapter.MyAdapter();
            rcvDynamicImage.addItemDecoration(decoration);
            rcvDynamicImage.setLayoutManager(manager);
            rcvDynamicImage.setAdapter(adapter);

            tvAddress.setText(dynamicInfo.getAddress());
            tvBrowse.setText(dynamicInfo.getBrowse());
            tvComment.setText(dynamicInfo.getComment());
            tvGood.setText(dynamicInfo.getGood());
            Goods.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    String text = tvGood.getText().toString();
                    int goods = Integer.parseInt(text);
                    tvGood.setText(goods + 1 + "");
                }
            });
            Comment.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(context, DynamicCommentActivity.class);
                    intent.putExtra("dynamicInfo", dynamicInfo);
                    intent.putExtra("shareId", shareId);
                    context.startActivity(intent);
                }
            });
        }

        class MyAdapter extends RecyclerView.Adapter<DynamicAdapter.MyAdapter.ViewHolder> {

            @Override
            public DynamicAdapter.MyAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
                View inflate = LayoutInflater.from(context).inflate(R.layout.item_dynamic_image, null);
                DynamicAdapter.MyAdapter.ViewHolder holder = new DynamicAdapter.MyAdapter.ViewHolder(inflate);
                return holder;
            }

            @Override
            public void onBindViewHolder(DynamicAdapter.MyAdapter.ViewHolder holder, final int position) {
                Picasso.with(context)
                        .load("http://192.168.12.248:8080/" + checkList.get(position))
                        .resize(UIUtils.dip2px(100), UIUtils.dip2px(70))
                        .centerCrop()
                        .config(Bitmap.Config.RGB_565)
                        .into(holder.threeImageView);
                holder.threeImageView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent intent = new Intent(context, ShowBogImageActivity.class);
                        intent.putStringArrayListExtra("checkList", checkList);
                        intent.putExtra("position", position);
                        context.startActivity(intent);
                    }
                });
            }

            @Override
            public int getItemCount() {
                return checkList.size();
            }

            class ViewHolder extends RecyclerView.ViewHolder {
                ThreeImageView threeImageView;

                public ViewHolder(View itemView) {
                    super(itemView);
                    threeImageView = (ThreeImageView) itemView.findViewById(R.id.iv_dynamic_image);
                }
            }
        }
    }

}
